/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net;

import net.*;
import java.net.*;
import java.io.*;
import java.util.*;

import message.handler.*;


/**
 *
 * @author antonio
 */


/*
 *  ServerSniffer è il server che riceve i segnali
 *  sniffati da NetStumbler.
 *
 *  - 1 - riceve info da NS
 *  - 2 - crea il tipo di handler message corretto
 *  - 3 - richiama il metodo handle() del handler
 *        appena creato. Il metodo handle() crea un
 *        un oggetto di tipo Message appropriato alle
 *        info ricevute da NS.
 *        Successivamente il Message si occuperà di
 *        processare le info correttamente.
 *
 * */

public class ServerSniffer extends Thread{

    public void run()
    {
        try
        {
            ServerSocket socket = new ServerSocket(8888);

            while(true)
            {
                Socket connection = socket.accept();
                WorkerServerSniffer worker = new WorkerServerSniffer(connection);
                worker.start();
            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
class WorkerServerSniffer extends Thread
{
     private Socket socket;
     private InetAddress local_ip;
     private InetAddress remote_ip;
     private int local_port;
     private int remote_port;

     private boolean quit = false;

     public WorkerServerSniffer(Socket socket)
     {
         this.socket = socket;
         this.local_ip = socket.getLocalAddress();
         this.remote_ip = socket.getInetAddress();
         this.local_port = socket.getLocalPort();
         this.remote_port = socket.getPort();
     }

     public void run()
     {
         try{

             InputStream input = this.socket.getInputStream();
             Scanner readerInput = new Scanner(input);

             while(!this.quit)
             {
                String line = readerInput.nextLine();

                MessageHandlerFactory makerHandler = new MessageHandlerFactory();
                MessageHandler handler = makerHandler.getHandlerForType(line);

                this.quit = handler.handle(readerInput);

             }
         }catch(Exception e)
         {
             e.printStackTrace();
         }
     }
}